<?php

/**
 * 打单系统 Ordering Software
 *
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2025.05.08
*/

namespace App\Services\User;

use App\Models\User;
use App\Models\UserAdd;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Exception;

abstract class UserService
{
    /**
     * 通过邮箱获取用户
     *
     * @param string $email
     * @return User|null
     */
    protected function findUserByEmail(string $email): ?User
    {
        return User::where('email', $email)->first();
    }

    /**
     * 增加用户
     *
     * @param array $data
     * @param string $role
     * @param int $teamId
     * @return User
     */
    protected function create(array $data, string $role = 'member', int $teamId = 1): User
    {
        return DB::transaction(function() use ($data, $role, $teamId) {

            $user = User::firstOrCreate([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);

            if (!$user->wasRecentlyCreated) {
                throw new Exception('The email has already been taken.');
            }

            UserAdd::create([
                'user_id' => $user->id,
                'saytext' => '',
                'spacegg' => '',
                'login_count' => 0
            ]);
            // 团队
            setPermissionsTeamId($teamId);
            // 分配默认角色
            $user->assignRole($role);

            return $user;
        });
    }
}
